package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.entity.Commission;
import org.example.backend.entity.CommissionRule;
import org.example.backend.entity.Leader;
import org.example.backend.entity.Order;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.CommissionMapper;
import org.example.backend.mapper.CommissionRuleMapper;
import org.example.backend.mapper.LeaderMapper;
import org.example.backend.mapper.OrderMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 佣金控制器
 * 提供佣金规则和佣金记录的管理功能
 */
@RestController
@RequestMapping("/commission")
public class CommissionController {

    @Autowired
    private CommissionMapper commissionMapper;

    @Autowired
    private CommissionRuleMapper commissionRuleMapper;

    @Autowired
    private LeaderMapper leaderMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 分页查询佣金规则
     * @param current 当前页码
     * @param size 每页大小
     * @param name 规则名称（可选，模糊查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/rule/page")
    public ResponseEntity<Result<PageResult<CommissionRule>>> pageRule(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {

        Page<CommissionRule> page = new Page<>(current, size);

        LambdaQueryWrapper<CommissionRule> queryWrapper = Wrappers.<CommissionRule>lambdaQuery()
                .like(StringUtils.isNotBlank(name), CommissionRule::getName, name)
                .eq(status != null, CommissionRule::getStatus, status)
                .orderByAsc(CommissionRule::getMinAmount);

        Page<CommissionRule> rulePage = commissionRuleMapper.selectPage(page, queryWrapper);

        return ResponseUtil.success(new PageResult<>(rulePage.getTotal(), rulePage.getRecords()));
    }

    /**
     * 获取所有可用佣金规则
     * @return 佣金规则列表
     */
    @GetMapping("/rule/list")
    public ResponseEntity<Result<List<CommissionRule>>> listRule() {
        List<CommissionRule> rules = commissionRuleMapper.selectList(
                Wrappers.<CommissionRule>lambdaQuery()
                        .eq(CommissionRule::getStatus, 1)
                        .orderByAsc(CommissionRule::getMinAmount)
        );
        return ResponseUtil.success(rules);
    }

    /**
     * 获取佣金规则详情
     * @param id 规则ID
     * @return 规则详情
     */
    @GetMapping("/rule/{id}")
    public ResponseEntity<Result<CommissionRule>> getRuleById(@PathVariable Long id) {
        CommissionRule rule = commissionRuleMapper.selectById(id);
        if (rule == null) {
            return ResponseUtil.notFound("佣金规则不存在");
        }
        return ResponseUtil.success(rule);
    }

    /**
     * 新增佣金规则
     * @param rule 规则信息
     * @return 操作结果
     */
    @PostMapping("/rule")
    public ResponseEntity<Result<Void>> saveRule(@Valid @RequestBody CommissionRule rule) {
        // 检查规则名称是否已存在
        Long count = commissionRuleMapper.selectCount(Wrappers.<CommissionRule>lambdaQuery().eq(CommissionRule::getName, rule.getName()));
        if (count > 0) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "规则名称已存在");
        }

        // 检查金额范围是否有重叠
//        List<CommissionRule> existRules = commissionRuleMapper.selectList(null);
//        for (CommissionRule existRule : existRules) {
//            if ((rule.getMinAmount().compareTo(existRule.getMinAmount()) >= 0 && rule.getMinAmount().compareTo(existRule.getMaxAmount()) < 0) ||
//                (rule.getMaxAmount().compareTo(existRule.getMinAmount()) > 0 && rule.getMaxAmount().compareTo(existRule.getMaxAmount()) <= 0) ||
//                (rule.getMinAmount().compareTo(existRule.getMinAmount()) <= 0 && rule.getMaxAmount().compareTo(existRule.getMaxAmount()) >= 0)) {
//                throw new BusinessException(ResultCode.BUSINESS_ERROR, "金额范围与现有规则重叠");
//            }
//        }

        commissionRuleMapper.insert(rule);
        return ResponseUtil.created();
    }

    /**
     * 修改佣金规则
     * @param rule 规则信息
     * @return 操作结果
     */
    @PutMapping("/rule")
    public ResponseEntity<Result<Void>> updateRule(@Valid @RequestBody CommissionRule rule) {
        if (rule.getId() == null) {
            return ResponseUtil.badRequest("ID不能为空");
        }

        CommissionRule existRule = commissionRuleMapper.selectById(rule.getId());
        if (existRule == null) {
            return ResponseUtil.notFound("佣金规则不存在");
        }

        // 检查规则名称是否已被其他规则使用
        if (!existRule.getName().equals(rule.getName())) {
            Long count = commissionRuleMapper.selectCount(
                    Wrappers.<CommissionRule>lambdaQuery()
                            .eq(CommissionRule::getName, rule.getName())
                            .ne(CommissionRule::getId, rule.getId())
            );
            if (count > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "规则名称已存在");
            }
        }

        // 检查金额范围是否有重叠
//        List<CommissionRule> existRules = commissionRuleMapper.selectList(
//                Wrappers.<CommissionRule>lambdaQuery().ne(CommissionRule::getId, rule.getId())
//        );
//        for (CommissionRule er : existRules) {
//            if ((rule.getMinAmount().compareTo(er.getMinAmount()) >= 0 && rule.getMinAmount().compareTo(er.getMaxAmount()) < 0) ||
//                (rule.getMaxAmount().compareTo(er.getMinAmount()) > 0 && rule.getMaxAmount().compareTo(er.getMaxAmount()) <= 0) ||
//                (rule.getMinAmount().compareTo(er.getMinAmount()) <= 0 && rule.getMaxAmount().compareTo(er.getMaxAmount()) >= 0)) {
//                throw new BusinessException(ResultCode.BUSINESS_ERROR, "金额范围与现有规则重叠");
//            }
//        }

        commissionRuleMapper.updateById(rule);
        return ResponseUtil.success();
    }

    /**
     * 删除佣金规则
     * @param id 规则ID
     * @return 操作结果
     */
    @DeleteMapping("/rule/{id}")
    public ResponseEntity<Result<Void>> deleteRule(@PathVariable Long id) {
        CommissionRule rule = commissionRuleMapper.selectById(id);
        if (rule == null) {
            return ResponseUtil.notFound("佣金规则不存在");
        }

        commissionRuleMapper.deleteById(id);
        return ResponseUtil.success();
    }

    /**
     * 更新佣金规则状态
     * @param id 规则ID
     * @param status 状态值（0-禁用，1-启用）
     * @return 操作结果
     */
    @PutMapping("/rule/status")
    public ResponseEntity<Result<Void>> updateRuleStatus(@RequestParam Long id, @RequestParam Integer status) {
        CommissionRule rule = commissionRuleMapper.selectById(id);
        if (rule == null) {
            return ResponseUtil.notFound("佣金规则不存在");
        }

        CommissionRule updateRule = new CommissionRule();
        updateRule.setId(id);
        updateRule.setStatus(status);
        commissionRuleMapper.updateById(updateRule);

        return ResponseUtil.success();
    }

    /**
     * 分页查询佣金记录
     * @param current 当前页码
     * @param size 每页大小
     * @param leaderId 团长ID（可选，精确查询）
     * @param orderNo 订单编号（可选，模糊查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<Commission>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long leaderId,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer status) {

        Page<Commission> page = new Page<>(current, size);

        LambdaQueryWrapper<Commission> queryWrapper = Wrappers.<Commission>lambdaQuery()
                .eq(leaderId != null, Commission::getLeaderId, leaderId)
                .like(StringUtils.isNotBlank(orderNo), Commission::getOrderNo, orderNo)
                .eq(status != null, Commission::getStatus, status)
                .orderByDesc(Commission::getCreateTime);

        Page<Commission> commissionPage = commissionMapper.selectPage(page, queryWrapper);

        // 查询团长信息
        commissionPage.getRecords().forEach(commission -> {
            Leader leader = leaderMapper.selectById(commission.getLeaderId());
            if (leader != null) {
                // 可以添加额外信息，例如团长名称
                // 这里使用Map来存储额外信息
                Map<String, Object> extraInfo = new HashMap<>();
                extraInfo.put("leaderName", leader.getName());
                // 可以将额外信息添加到佣金对象中，但需要在Commission实体类中添加相应的字段
            }
        });

        return ResponseUtil.success(new PageResult<>(commissionPage.getTotal(), commissionPage.getRecords()));
    }

    /**
     * 计算订单佣金
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/calculate")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Map<String, Object>>> calculate(@RequestParam Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResponseUtil.notFound("订单不存在");
        }

        // 检查订单状态
        if (order.getStatus() != 3) {
            return ResponseUtil.badRequest("只能为已完成的订单计算佣金");
        }

        // 检查是否已计算过佣金
        Long count = commissionMapper.selectCount(Wrappers.<Commission>lambdaQuery().eq(Commission::getOrderId, orderId));
        if (count > 0) {
            throw new BusinessException(ResultCode.BUSINESS_ERROR, "该订单已计算过佣金");
        }

        // 查找适用的佣金规则
        BigDecimal orderAmount = order.getTotalAmount();
        CommissionRule rule = null;

        List<CommissionRule> rules = commissionRuleMapper.selectList(
                Wrappers.<CommissionRule>lambdaQuery()
                        .eq(CommissionRule::getStatus, 1)
                        .orderByAsc(CommissionRule::getMinAmount)
        );

        for (CommissionRule r : rules) {
            if (orderAmount.compareTo(r.getMinAmount()) >= 0 && orderAmount.compareTo(r.getMaxAmount()) <= 0) {
                rule = r;
                break;
            }
        }

        if (rule == null) {
            throw new BusinessException(ResultCode.BUSINESS_ERROR, "未找到适用的佣金规则");
        }

        // 计算佣金金额
        BigDecimal commissionAmount = orderAmount.multiply(rule.getRate()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

        // 创建佣金记录
        Commission commission = new Commission();
        commission.setLeaderId(order.getLeaderId());
        commission.setOrderId(order.getId());
        commission.setOrderNo(order.getOrderNo());
        commission.setAmount(commissionAmount);
        commission.setStatus(0); // 未结算
        commissionMapper.insert(commission);

        // 返回佣金信息
        Map<String, Object> result = new HashMap<>();
        result.put("commissionId", commission.getId());
        result.put("orderNo", order.getOrderNo());
        result.put("orderAmount", order.getTotalAmount());
        result.put("commissionRate", rule.getRate());
        result.put("commissionAmount", commissionAmount);

        return ResponseUtil.success(result);
    }

    /**
     * 结算佣金
     * @param id 佣金ID
     * @return 操作结果
     */
    @PutMapping("/settle/{id}")
    public ResponseEntity<Result<Void>> settle(@PathVariable Long id) {
        Commission commission = commissionMapper.selectById(id);
        if (commission == null) {
            return ResponseUtil.notFound("佣金记录不存在");
        }

        if (commission.getStatus() == 1) {
            return ResponseUtil.badRequest("该佣金已结算");
        }

        Commission updateCommission = new Commission();
        updateCommission.setId(id);
        updateCommission.setStatus(1); // 已结算
        commissionMapper.updateById(updateCommission);

        return ResponseUtil.success();
    }

    /**
     * 批量结算佣金
     * @param ids 佣金ID列表
     * @return 操作结果
     */
    @PutMapping("/settle-batch")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Map<String, Object>>> settleBatch(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return ResponseUtil.badRequest("请选择要结算的佣金");
        }

        int successCount = 0;
        int failCount = 0;

        for (Long id : ids) {
            Commission commission = commissionMapper.selectById(id);
            if (commission != null && commission.getStatus() == 0) {
                Commission updateCommission = new Commission();
                updateCommission.setId(id);
                updateCommission.setStatus(1); // 已结算
                commissionMapper.updateById(updateCommission);
                successCount++;
            } else {
                failCount++;
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("failCount", failCount);

        return ResponseUtil.success(result);
    }
}
